package com.zdp.rocketmq.send;

import com.zdp.rocketmq.config.JmsConfig;
import com.zdp.rocketmq.producer.ProducerBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * @author sesshomaru
 * 延迟消息
 * <p>
 * 就是消息发送后消费端要过一段时间才能收到
 * <p>
 * 延迟的级别
 * "1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h";
 * <p>
 * 原理:
 * 消息是在broker上的但是状态是不可消费的，只有到了延迟的结束时间，才可以被消费者消费
 */
@Slf4j
@RestController
public class DelayMessageController {

    @Autowired
    private ProducerBuilder producerBuilder;

    @RequestMapping("/api/v1/delay")
    public Object callback(String keys, String tag) throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
        Message message = new Message(JmsConfig.GENERAL_TOPIC, tag, keys, ("hello rocketmq = " + keys).getBytes());
        // 设置延迟消息
        message.setDelayTimeLevel(3);
        SendResult sendResult = producerBuilder.getProducer().send(message);
        log.info("发送延迟消息:{}", sendResult.toString());
        return new HashMap<>(1);
    }
}
